<!--
* description: 采购管理-网点订单审核_总部
* author: hm
* createdDate: 2021-07-16
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="dynamicApiConfigs"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-is-fix-choose="false"
      :dynamic-is-fix-index="false"
      :dynamic-api-style="'restful'"
      :callback-obj="callbackObj"
    >
      <!--      驳回原因-->
      <template #rejectReason="{row, col}">
        <el-input
          v-model="row['rejectReason']"
          placeholder="请输入驳回原因"
          clearable="true"
        ></el-input>
      </template>
      <!--      备注-->
      <template #remark="{row, col}">
        <el-input
          v-model="row['remark']"
          placeholder="备注"
          clearable="true"
        ></el-input>
      </template>
    </one-table-template>
    <AuditAllocation
      :is-view-pop-windows="isViewPopWindows"
      :dynamic-edit-row-data="editRowData"
      @close="close"
    />
  </div>
</template>

<script>
// import { formMixins } from "@/components/mixins/formMixins";
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/vehicleManagement'
import AuditAllocation from './auditAllocation'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'
import { exportExcel } from '@/utils/getTimeString.js'

export default {
  name: 'PartOrderHQAudit',
  components: {
    OneTableTemplate,
    AuditAllocation
  },
  mixins: [oneTableWithViewTemplateMixins],
  data() {
    null
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      selectiondata: [],
      editRowData: {},
      isViewPopWindows: false,
      // dynamicApiConfigs: vehiclePdiPriceInquirys.queryByPage,
      dynamicApiConfigs: vehiclePdiPriceInquirys.queryDlrDoneByPage,
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'controlBtn',
              label: '操作', // 操作
              codeField: 'controlBtn',
              width: 100,
              align: 'center',
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '明细', // 编辑
                  align: 'center',
                  codeField: 'editControlBtn',
                  clickEvent: (index) => {
                    this.isViewPopWindows = true
                    this.editRowData = this.$utils.deepCopy(
                      this.$refs['multipleTable'].list[index]
                    )
                  },
                  component: () => import('@/components/org/linkButton')
                },
                {
                  compKey: 'propKey2',
                  labelName: '附件', // 附件下载
                  align: 'center',
                  codeField: 'downloadBtn',
                  rowFileds: 'show:attachmentUrl--null',
                  clickEvent: (index) => {
                    this.fileDownload(index)
                  },
                  component: () => import('@/components/org/linkButton')
                }
              ]
            },
            {
              prop: 'dlrCode',
              label: '网点编码',
              align: 'center'
            },
            {
              prop: 'dlrShortName',
              label: '网点名称',
              align: 'center',
              width: 110
            },
            {
              prop: 'purOrderCode',
              label: '订单号',
              align: 'center',
              width: 150
            },
            {
              prop: 'purOrderTypeName',
              label: '订单类型',
              align: 'center'
            },
            {
              prop: 'purDate',
              label: '订货日期',
              align: 'center'
            },
            {
              prop: 'VIN',
              label: 'VIN码',
              align: 'center'
            },
            {
              prop: 'orderVariety',
              label: '订货品种数',
              align: 'center'
            },
            {
              prop: 'purAmount',
              label: '订货金额',
              align: 'center'
            },
            // {
            //   prop: 'transportModeName',
            //   label: '运输方式',
            //   align: 'center'
            // },
            {
              prop: 'rejectReason',
              label: '驳回原因+',
              align: 'center',
              isSlot: true,
              width: 170,
            },
            {
              prop: 'remark',
              label: '备注+',
              align: 'center',
              isSlot: true,
              width: 150
            }
          ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 库存状态
            {
              compKey: 'compKey1',
              labelName: '网点：',
              codeField: 'dlrId',
              textField: 'dlrShortName',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              type: 'inputText',
              isMust: true,
              // isRequire: true,
              dataToObject: {
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrShortName: '',
                  dlrCode: ''
                },
                oFields: 'dlrId,dlrShortName',
                returnField: {
                  prop: 'dlrShortName',
                  label: '网点名称'
                },
                api: api.queryOrgDlrCodes
              },
              span: 6
            },
            {
              compKey: 'compKey2',
              labelName: '订单号：',
              codeField: 'purOrderCode',
              lookuptype: 'VE0212',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 6
            },
            // 车辆状态
            {
              compKey: 'compKey3',
              labelName: '订货日期：',
              codeField: 'startDate,endDate',
              lookuptype: 'VE0207',
              component: () => import('@/components/org/datePicker/andtDatePicker'),
              type: 'YYYY-MM-DD',
              format: 'yyyy-MM-dd',
              dateOptionsType: '0',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey4',
              labelName: '订单类型：',
              codeField: 'purOrderType',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                // api: vehiclePdiPriceInquirys.queryDropDownList
                api: vehiclePdiPriceInquirys.queryDlrDoneDropDownList
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            }
          ],
      tableButtons: [
        {
          conmpKey: 'btenKey1',
          type: 'primary',
          size: 'small',
          text: '查询',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          position: 'right'
        },
        {
          conmpKey: 'btenKey2',
          type: '',
          size: 'small',
          clickEvent: async() => {
            if (!this.selectiondata.length) return this.$message('请先选择要审核分配的数据！')
            let response
            const variables = { list: this.selectiondata }
            const apiUrl = '/mp/e3sh/spareparts/sparePartsOrderReviewService/updateReview.do'
            try {
              response = await this.$requestAPI({ variables, apiUrl })
            } catch (e) {
              return
            }
            if (response.result === '1') {
              this.queryTable()
              this.$message(response.msg ? response.msg : '审核分配成功!')
              this.selectiondata = []
            } else {
              this.$alert(response.msg || '审核分配失败!', '提示')
            }
          },
          text: '审核分配',
          name: 'auditButton',
          position: 'right'
        },
        {
          conmpKey: 'btenKey3',
          type: '',
          size: 'small',
          clickEvent: () => this.reject(),
          text: '驳回',
          name: 'reject',
          position: 'right'
        },
        {
          conmpKey: 'btenKey5',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: this.$t('sys.button.export'),
          name: 'export',
          position: 'right' // 导出
        },
        {
          conmpKey: 'btenKey6',
          type: '',
          size: 'small',
          name: 'reset',
          text: '重置',
          clickEvent: () => this.reset(),
          position: 'right'
        }
      ],
      formField: this.$utils.getFormField(this, {
        dlrId: '', // 网点
        dlrShortName: '',
        startDate: '',
        endDate: '',
        purOrderCode: '', // 订单号
        // purDate: "", //订货日期
        purOrderType: '' // 订单类型
      }),
      // 回调方法对象
      callbackObj: {
        // 网格点击回调事件
        onRowClick: (currentRow) => {
          // this.onRightRowClick(currentRow);
        },
        // 手动勾选网格时，拿到勾选网格的数据
        // onCheckSelect: (selection, row) => {
        //   this.selectiondata = selection
        // },
        onCheckSelectChange: (selection) => {
          // this.onCheckSelectChange1(selection)
          this.selectiondata = selection
        }
      }
    }
  },
  mounted() {

  },
  watch: {
    '$route': {
      handler(route) {
        if (route.name === 'partOrderHQAudit') {
          this.queryTable()
        }
      },
      immediate: true
    }
  },
  methods: {
    close() {
      this.isViewPopWindows = false
      this.queryTable(1)
    },
    // 驳回
    reject() {
      if (!this.selectiondata || this.selectiondata.length == 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'warn',
          uration: 1000
        })
      } else {
        const that = this
        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: vehiclePdiPriceInquirys.updateDlrDoneTurnDown,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: { list: this.selectiondata }
        }
        // 转换了中台请求格式数据
        var paramD = that.$getParams(queryObj)
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then((response) => {
          if (response.result === '1') {
            this.$message({
              message: '已驳回',
              type: 'success',
              duration: 2000
            })
            this.queryTable(1)
          } else {
            // 保存失败
            this.$message({
              message: '保存失败',
              type: 'warn',
              uration: 2000
            })
          }
        })
      }
    },
    // 导出
    exportExcel111() {
      exportExcel(
        this.formField,
        vehiclePdiPriceInquirys.exportDlrDoneDetails.APIUrl,
        vehiclePdiPriceInquirys.exportDlrDoneDetails.ServiceCode,
        '网点订单审核_总部'
      )
    },
    // 附件下载
    // 下载附件
    fileDownload(index) {
      if (!this.$refs['multipleTable'].list[index].attachmentUrl) {
        this.$message({
          message: "无附件",
          type: "warning",
        });
        return false;
      }

      const loading = this.$loading({ text: `正在下载附件` });
      this.$requestAPI({
        method: "GET",
        apiUrl: this.$refs['multipleTable'].list[index].attachmentUrl,
        variables: {
          dataType: "excel",
        },
      })
        .then((res) => {
          this.$utils.downloadFile(res, this.$refs['multipleTable'].list[index].attachmentName);
        })
        .catch((err) => {})
        .finally(() => {
          loading.close();
        });
    },
  }
}
</script>

<style>
</style>
